<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 配置中心->参数限流
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="10">
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.resource" placeholder="资源标识" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.instance" placeholder="应用实例" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.appCode" placeholder="所属应用" class="handle-select">
                            <el-option v-for="item in appList"
                                       :label="item.appName"
                                       :value="item.appCode">
                                <span style="float: left">{{ item.appName }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="12" style="text-align: left">
                        <el-button type="primary" icon="el-icon-folder-add" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :xs="24" :sm="12" style="text-align: right">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" icon="el-icon-refresh" @click="clearQueryForm">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table border class="table"
                      ref="multipleTable"
                      :data="tableData"
                      header-cell-class-name="table-header"
                      @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="resource" label="资源标识" width="280" align="center"></el-table-column>
                <el-table-column prop="appCode" label="所属应用"></el-table-column>
                <el-table-column prop="limitParam" label="限流参数"></el-table-column>
                <el-table-column prop="limitMode" label="限流模式" align="center"></el-table-column>
                <el-table-column prop="controlStrategy" label="流控策略" align="center"></el-table-column>
                <el-table-column prop="controlBehavior" label="流控效果" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center"></el-table-column>
                <el-table-column label="操作" width="130" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                   @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination background
                               layout="total, prev, pager, next"
                               :current-page="query.pageVo.pageNo"
                               :page-size="query.pageVo.pageSize"
                               :total="pageTotal"
                               @current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="限流规则管理" :visible.sync="editVisible" width="60%" :lock-scroll="false">

            <el-form ref="form" :model="formData" label-width="80px">
                <el-row :gutter="10">
                    <el-col :md="24">
                        <el-form-item label="资源标识">
                            <el-input v-model="formData.resource"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12">
                        <el-form-item label="所属应用">
                            <el-select v-model="formData.appCode" placeholder="所属应用" class="handle-select">
                                <el-option v-for="item in appList"
                                           :label="item.appName"
                                           :value="item.appCode">
                                    <span style="float: left">{{ item.appName }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12">
                        <el-form-item label="请求来源">
                            <el-input v-model="formData.limitApp"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :md="24">
                        <el-form-item label="限流参数">
                            <el-input v-model="formData.limitParam"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :md="12">
                        <el-form-item label="流控模式">
                            <el-radio-group v-model="formData.limitMode">
                                <el-radio-button v-for="item in limitModeList" :label="item.value">
                                    {{ item.label }}
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12">
                        <el-form-item label="阈值类型">
                            <el-radio-group v-model="formData.grade">
                                <el-radio-button v-for="item in gradeList" :label="item.value">
                                    {{ item.label }}
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12">
                        <el-form-item label="限流阈值">
                            <el-input-number size="medium" v-model="formData.threshold" :min="0" :max="1000000" placeholder="限流阈值"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12">
                        <el-form-item label="阈值周期">
                            <el-input-number size="medium" v-model="formData.thresholdCycle" :min="1" :max="600" placeholder="单位：秒"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :md="12">
                        <el-form-item label="流控策略">
                            <el-radio-group v-model="formData.controlStrategy">
                                <el-radio-button v-for="item in controlStrategyList" :label="item.value">
                                    {{ item.label }}
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" v-show="formData.controlStrategy!='direct'">
                        <el-form-item v-if="formData.controlStrategy=='reference'" label="关联资源">
                            <el-input size="medium" v-model="formData.limitRule.controlStrategyValue"></el-input>
                        </el-form-item>
                        <el-form-item v-if="formData.controlStrategy=='chain'" label="链路信息">
                            <el-input size="medium" v-model="formData.limitRule.controlStrategyValue"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :md="12">
                        <el-form-item label="流控效果">
                            <el-radio-group v-model="formData.controlBehavior">
                                <el-radio-button v-for="item in controlBehaviorList" :label="item.value">
                                    {{ item.label }}
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" v-show="formData.controlBehavior!='fail-fast'">
                        <el-form-item v-if="formData.controlBehavior=='warm-up'" label="预热时长">
                            <el-input size="medium" v-model="formData.limitRule.controlBehaviorValue" placeholder="预热时长，单位：毫秒"></el-input>
                        </el-form-item>
                        <el-form-item v-if="formData.controlBehavior=='wait'" label="等待时长">
                            <el-input size="medium" v-model="formData.limitRule.controlBehaviorValue" placeholder="排队等待时长，单位：耗秒"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :md="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="formData.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">保 存</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import { doFindParamRulesByPage, doSaveParamRule } from '../../api/configic/flowParamRule';
    import { fetchDictByIndex } from '../../api/resic/dictionary';
    import { listApp } from '../../api/appic/appInfo';
    import { OnionUtils } from '../../utils/onion-utils';

    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    data:{
                    },
                    pageVo:{
                        pageNo: 1,
                        pageSize: 10
                    }
                },
                pageTotal: 0,
                editVisible: false,
                formData: {},
                tableData:[],
                appList:[],
                limitModeList:[{label:"通用", value:"common"},{label:"集群", value:"cluster"}],
                gradeList:[{label:"QPS", value:"qps"},{label:"并发数", value:"cps"}],
                controlStrategyList:[{label:"直接", value:"direct"},{label:"关联", value:"reference"},{label:"链路", value:"chain"}],
                controlBehaviorList:[{label:"失败", value:"fail-fast"},{label:"预热", value:"warm-up"},{label:"等待", value:"wait"}],
                id: -1,
                idx: -1
            };
        },
        //初始化页面数据
        created() {
            this.initData();
            this.findPage();
        },

        //方法区
        methods: {
            dateFormat(row,column){
                let data = row[column.property]
                if (data ===null) {
                    return ''
                }
                let dt = new Date(data)
                return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
                        + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
            },
            //初始化页面数据
            initData(){
                let appQueryParam = {
                    param: {},
                    pageVo: { pageNo: 1, pageSize: 100 }
                };
                listApp(appQueryParam).then(result => {
                    this.appList = result.data;
                });
            },
            //分页列表查询
            findPage(){
                doFindParamRulesByPage(this.query).then(result=>{
                    this.tableData = result.data.rows;
                    this.pageTotal = result.data.total || 50;
                })
            },
            //查询按钮事件
            handleQuery(){
                this.findPage();
            },
            //新增限流规则
            handleAdd(){
                if(OnionUtils.isEmpty(this.query.data.appCode)){
                    this.$alert("请选择应用系统!");
                    return;
                }
                this.idx = -1;
                this.formData ={
                                ruleType: "param",
                                appCode: this.query.data.appCode,
                                limitMode: "common",
                                grade: "qps",
                                controlStrategy: "direct",
                                controlBehavior: "fail-fast",
                                limitRule: {}
                               }
                this.editVisible = true;
            },
            //编辑限流规则
            handleEdit(index, row) {
                this.idx = index;
                this.formData = row;
                this.editVisible = true;
            },
            //删除限流规则
            handleDelete(index, row){
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    doDeleteParamRule(this.tableData[index].id).then(result => {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    });
                }).catch(() => {
                    this.$alert('异常！');
                });
            },
            //保存限流规则信息
            handleSave(){
                doSaveParamRule(this.formData).then(result=>{
                    this.$message.success(`保存成功！`);
                    if(this.idx != -1){
                        this.$set(this.tableData, this.idx, result.data);
                    }else{
                        this.findPage();
                    }
                    this.editVisible = false;
                });
            },
            //清空条件区
            clearQueryForm(){
                this.query.data = {};
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.findPage();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 10px;
    }
    .handle-select {
        width: 100%;
    }
    .handle-input {
        width: 100%;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }
</style>